package com.shwread.android.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.NewActionHelp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.AtlasActivity;
import com.shwread.android.qysw.activity.AtlasSeeActivity;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.CommentListActivity;
import com.shwread.android.qysw.activity.ImageTextActivity;
import com.shwread.android.qysw.activity.NewBookDetailActivity;
import com.shwread.android.qysw10000136.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.constant.ResultCode;
import com.shwread.httpsdk.http.base.AbstractHttpPostDracom;
import com.shwread.httpsdk.http.callback.ActionListener;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryCommentPraiseNumAction;

import org.apache.http.Header;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import logic.bean.AudioAndVideo;
import logic.bean.BookInfo;
import logic.bean.ImageCollection;
import logic.bean.MultiNews;
import logic.bean.NumberInfo;
import logic.bean.RegionContentItemBean;
import logic.bean.SingleBook;
import logic.bean.SingleNews;
import logic.constants.AppConfig;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.DateUtil;
import logic.util.PicassoUtil;
import logic.util.Util;

/**
 * 企业专区的内容
 *
 * @author zouqp
 *         2015-01-15
 */

public class RegionContentView extends LinearLayout
        implements OnScrollListener, OnItemClickListener {
    public static final int PAGESIZE = 5;
    public static final int CONTENT_ITEM_MAX_SIZE = 60;
    public static final int IMAGE_COUNT = 5;
    private static final char REGION_SPLITOR = 8;
    // total list items, used to detect is at the bottom of listview.
    private int mTotalItemCount = 0;
    private MyListView mContentListView;
    private long moduleId;// 模块id
    private Context mContext;//
    private ContentAdapter mContentAdapter;
    private boolean canUpdate = true;
    private boolean hasMore = true;
    List<RegionContentItemBean> mContentItemList = new ArrayList<>(); //内容项列表
    private int currentPage = 1;
    private int i = 0;
    private ImageView switchImg;
    private View switchView;
    private AnimationDrawable switchDrawable;
    private BaseBusinessActivity baseActivity;
    private RegionContentViewListener contentViewListener;
    private long currentPublishTime = 0;
    private RelativeLayout rl_blank_content;
    private int myRefreshFlag = 2; //1为 下拉刷新， 2为得到数据
    private String targetType;
    private String targetValue;
    private TextView tv_comments_count;
    //TODO 解决流量消耗过多的问题,暂定方案
    private Map<Integer, View> views;//view对象缓存

    /**
     * @param context
     */
    public RegionContentView(Context context) {
        super(context);
        mContext = context;
        initWithContext(context);
    }

    public RegionContentView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initWithContext(context);
    }

    @SuppressLint("NewApi")
    public RegionContentView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initWithContext(context);
    }

    private void initWithContext(Context context) {
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        LinearLayout containerView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.region_content_layout, null);
        mContentListView = (MyListView) containerView.findViewById(R.id.lv_region_content);
        switchImg = (ImageView) containerView.findViewById(R.id.column_switch_img);
        switchView = containerView.findViewById(R.id.column_switch_layout);
        rl_blank_content = (RelativeLayout) containerView.findViewById(R.id.rl_blank_content);

        addView(containerView, lp);
        mContentListView.setOnScrollListener(this);
        mContentListView.setOnItemClickListener(this);
        mContentAdapter = new ContentAdapter();
        views = new HashMap<>();
        mContentListView.setAdapter(mContentAdapter);
    }

    public void setBaseActivity(BaseBusinessActivity baseActivity) {
        this.baseActivity = baseActivity;
    }

    public void updateTheCommentsCount() {
        //获取评论数
        new QryCommentPraiseNumAction(mContext, targetType, targetValue, new BookCommentsNumberActionListener()).start();
    }

    /**
     * @param moduleId
     * @param refreshFlag 1为 下拉刷新， 2为得到数据
     */
    public void getModelData(long moduleId, int refreshFlag) {
        this.moduleId = moduleId;
        mContentListView.setFocusable(false);
        //this.moduleId = 100;
        this.myRefreshFlag = refreshFlag;
        if (refreshFlag == 2) {
            mContentItemList.clear();
            views.clear();
            mContentAdapter.notifyDataSetChanged();
            updateSwitchView(0);//显示动画
        }

        currentPage = 1;
        currentPublishTime = 0;
        //todo 调用真实的接口， 获取数据
        getContentItemDatas();
    }

    public int getTotalItemCount() {
        return mTotalItemCount;
    }

    public void getNextPage() {
        if (mTotalItemCount >= CONTENT_ITEM_MAX_SIZE) return;
        currentPage++;
        //getFakeContentItemDatas();
        getContentItemDatas();
    }

    public boolean isGotMaxSize() {
        return mTotalItemCount >= CONTENT_ITEM_MAX_SIZE;
    }

    public boolean getHasMore() {
        return hasMore;
    }

    public void setRegionContentViewListener(RegionContentViewListener contentViewListener) {
        this.contentViewListener = contentViewListener;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        // send to user's listener
//		mTotalItemCount = totalItemCount;
//		if (canUpdate && hasMore && totalItemCount != 0 && totalItemCount - firstVisibleItem - visibleItemCount <= 5 ) {
//			getFakeContentItemData( );
//			mContentAdapter.notifyDataSetChanged();
//		}
    }

    private void refreshUIData() {
        mTotalItemCount = mContentItemList.size();
        if (currentPage == 1) {//刷新
            views.clear();
            mContentAdapter.notifyDataSetChanged();
            if (myRefreshFlag == 2) {
                updateSwitchView(1);//隐藏动画
            }
            if (contentViewListener != null) {
                contentViewListener.OnLoadDataCompleted(1);
            }
        } else {//取下一页
            if (contentViewListener != null) {
                contentViewListener.OnLoadDataCompleted(2);//装载更多
            }
            mContentAdapter.notifyDataSetChanged();
        }
    }

    /******************************
     * list 的 item click 方法
     *****************************************/

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        RegionContentItemBean contentItem = mContentItemList.get(position);
        //
        String contentType = contentItem.getType();
        if (contentType.equalsIgnoreCase("1")) { //单条资讯
            //todo 跳转到图文详情
            SingleNews singleNews = contentItem.getSingleNews();
            gotoImageTextActivity(singleNews.getHtmlUrl(), singleNews.getTitle(), singleNews.getModelContentDetailId() + "");
        } else if (contentType.equalsIgnoreCase("2")) {//多条资讯
            //每个已经处理了， 这里不需要处理
        } else if (contentType.equalsIgnoreCase("3")) {//音频

        } else if (contentType.equalsIgnoreCase("4")) {//视频

        } else if (contentType.equalsIgnoreCase("5")) { //图集
            //todo 跳转到查看图集图片
            gotoImageViewerActivity(position/*,2*/);
        } else if (contentType.equalsIgnoreCase("6")) { //单本书籍
            //跳转到书籍详情
            SingleBook singleBook = contentItem.getSingleBook();
            BookInfo bookInfo = singleBook.getBookInfo();
            if (bookInfo == null) return;
            //#ifdef SHOW_OLDBOOKDETAIL
            //$ Intent intent = new Intent(mContext, BookDetailActivity.class);
            //#else
            Intent intent = new Intent(mContext, NewBookDetailActivity.class);
            //#endif
            bookInfo.setAuthor("");
            intent.putExtra("BookInfo", bookInfo);
            mContext.startActivity(intent);
        }
    }

    /**
     * 跳转到图文详情页
     *
     * @param url
     */
    private void gotoImageTextActivity(String url, String title, String contentDetailId) {
        Intent intent = new Intent(mContext, ImageTextActivity.class);
        intent.putExtra(DefaultConsts.req_url_s, url);
        intent.putExtra(DefaultConsts.title_s, title);
        intent.putExtra(DefaultConsts.COMMENT_TARGET_TYPE, "2");
        intent.putExtra(DefaultConsts.COMMENT_TARGET_VALUE, contentDetailId);
        mContext.startActivity(intent);
    }

    /**
     * 跳转到查看图集的页面
     *
     * @param position 1 为直接进入查看, 2 为可能要进入到瀑布流页面
     */
    private void gotoImageViewerActivity(int position/*, int type*/) {
        int imgCounts = 0;
        RegionContentItemBean contentItem = mContentItemList.get(position);
        ImageCollection imageSet = contentItem.getImageSet();
        imgCounts = imageSet.getImageCollectionNum();
        Intent intent;
        if (imgCounts == 0) {
            Toast.makeText(mContext, "图集已下架", Toast.LENGTH_SHORT).show();
            return;
        }
        if (/*type == 1 || ( type == 2 && */imgCounts <= IMAGE_COUNT/*) */) {
            //直接进入看图片
            intent = new Intent(mContext, AtlasSeeActivity.class);
            intent.putExtra(AtlasSeeActivity.FROM_TYPE, DefaultConsts.TAG_FROM_ENTERPRISE);
            intent.putExtra(AtlasSeeActivity.IMAGE_COUNT, imgCounts);
        } else {//进入到瀑布流页面
            intent = new Intent(mContext, AtlasActivity.class);
            intent.putExtra(AtlasActivity.ATLAS_NAME, imageSet.getTitle());
        }
        //todo  设置图集的数据
        intent.putExtra(AtlasActivity.ATLAS_ID, imageSet.getImageCollectionId());
        mContext.startActivity(intent);
    }

    /******************************
     * list 的适配器
     *****************************************/
    private class ContentAdapter
            extends
            BaseAdapter {
        @Override
        public int getCount() {
            if (mContentItemList == null) {
                return 0;
            } else {
                Log.e("" + i++, "Count:" + mContentItemList.size());
                return mContentItemList.size();
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View view, ViewGroup parent) {
            if (views.get(position) != null) {
                return views.get(position);
            }
            RegionContentItemBean contentItem = mContentItemList.get(position);
            String contentType = contentItem.getType();
            if (contentType.equalsIgnoreCase("1")) { //单条资讯
                view = LayoutInflater.from(mContext).inflate(R.layout.region_singleinfo_item, null);
                SingleinfoViewHolder singleInfo = new SingleinfoViewHolder();
                singleInfo.tv_info_title = (TextView) view.findViewById(R.id.tv_info_title);
                singleInfo.tv_info_from = (TextView) view.findViewById(R.id.tv_info_from);
                singleInfo.tv_item_introduce = (TextView) view.findViewById(R.id.tv_item_introduce);
                singleInfo.im_bigimage = (ImageView) view.findViewById(R.id.im_bigimage);
                singleInfo.im_leftimage = (ImageView) view.findViewById(R.id.im_leftimage);
                singleInfo.im_rightimage = (ImageView) view.findViewById(R.id.im_rightimage);
                singleInfo.tv_publishtime = (TextView) view.findViewById(R.id.tv_publishtime);
                singleInfo.tv_comments_count = (TextView) view.findViewById(R.id.tv_comments_count);
                singleInfo.im_comments = (ImageView) view.findViewById(R.id.im_comments);

                // 填充数据
                SingleNews singleNews = contentItem.getSingleNews();
                singleInfo.tv_info_title.setText(singleNews.getTitle());
                String fromSource = singleNews.getFromSource();
                if (Util.isEmpty(fromSource)) {
                    singleInfo.tv_info_from.setVisibility(View.GONE);
                } else {
                    singleInfo.tv_info_from.setText("来源：" + fromSource);
                }
                if (Util.isEmpty(singleNews.getShortDesc())) {
                    singleInfo.tv_item_introduce.setVisibility(View.GONE);
                } else {
                    singleInfo.tv_item_introduce.setText(singleNews.getShortDesc());
                }
                int layoutType = singleNews.getLayoutType();
                if (layoutType == 1) {//无图
                    singleInfo.im_bigimage.setVisibility(View.GONE);
                    singleInfo.im_leftimage.setVisibility(View.GONE);
                    singleInfo.im_rightimage.setVisibility(View.GONE);
                } else if (layoutType == 2) {//大图
//					singleInfo.im_bigimage.setImageUrl(singleNews.getCoverImageUrl(), R.drawable.bg_big_image);
                    PicassoUtil.load(mContext, singleNews.getCoverImageUrl(), R.drawable.bg_big_image, singleInfo.im_bigimage);

                    singleInfo.im_leftimage.setVisibility(View.GONE);
                    singleInfo.im_rightimage.setVisibility(View.GONE);
                } else if (layoutType == 3) {//小左图
                    singleInfo.im_bigimage.setVisibility(View.GONE);
//					singleInfo.im_leftimage.setImageUrl(singleNews.getCoverImageUrl(), R.drawable.bg_small_image);
                    PicassoUtil.load(mContext, singleNews.getCoverImageUrl(), R.drawable.bg_small_image, singleInfo.im_leftimage);

                    singleInfo.im_rightimage.setVisibility(View.GONE);
                } else if (layoutType == 4) {//小右图
                    singleInfo.im_bigimage.setVisibility(View.GONE);
                    singleInfo.im_leftimage.setVisibility(View.GONE);
//					singleInfo.im_rightimage.setImageUrl(singleNews.getCoverImageUrl(),R.drawable.bg_small_image);
                    PicassoUtil.load(mContext, singleNews.getCoverImageUrl(), R.drawable.bg_big_image, singleInfo.im_rightimage);

                }
                singleInfo.tv_publishtime.setText(DateUtil.getRegionTime(contentItem.getPublishTime()));
                singleInfo.tv_comments_count.setText(singleNews.getCommentNum() + "");
                singleInfo.im_comments.setTag("2" + REGION_SPLITOR + singleNews.getModelContentDetailId());//专区内容的资讯
                singleInfo.im_comments.setOnClickListener(commentsOnclickListener);

                view.setTag(singleNews.getHtmlUrl());
            } else if (contentType.equalsIgnoreCase("2")) {//多条资讯
                view = LayoutInflater.from(mContext).inflate(R.layout.region_multiinfo_item, null);
                MultiinfoViewHolder multiInfo = new MultiinfoViewHolder();
                multiInfo.tv_biginfo_title = (TextView) view.findViewById(R.id.tv_biginfo_title);
                multiInfo.tv_smallinfo1 = (TextView) view.findViewById(R.id.tv_smallinfo1);
                multiInfo.tv_smallinfo2 = (TextView) view.findViewById(R.id.tv_smallinfo2);
                multiInfo.tv_smallinfo3 = (TextView) view.findViewById(R.id.tv_smallinfo3);

                multiInfo.tv_splitor1 = (TextView) view.findViewById(R.id.tv_splitor1);
                multiInfo.tv_splitor2 = (TextView) view.findViewById(R.id.tv_splitor2);
                multiInfo.tv_splitor3 = (TextView) view.findViewById(R.id.tv_splitor3);

                multiInfo.im_bigimage = (ImageView) view.findViewById(R.id.im_bigimage);
                multiInfo.im_smallimage1 = (ImageView) view.findViewById(R.id.im_smallimage1);
                multiInfo.im_smallimage2 = (ImageView) view.findViewById(R.id.im_smallimage2);
                multiInfo.im_smallimage3 = (ImageView) view.findViewById(R.id.im_smallimage3);

                multiInfo.fl_biginfo = view.findViewById(R.id.fl_biginfo);
                multiInfo.rl_smallinfo1 = view.findViewById(R.id.rl_smallinfo1);
                multiInfo.rl_smallinfo2 = view.findViewById(R.id.rl_smallinfo2);
                multiInfo.rl_smallinfo3 = view.findViewById(R.id.rl_smallinfo3);

                multiInfo.tv_publishtime = (TextView) view.findViewById(R.id.tv_publishtime);

                // 填充数据
                MultiNews multiNews = contentItem.getMutilNews();
                int count = multiNews.getNewsCount();
                for (int i = 0; i < count; i++) {
                    setMultiNewsContent(position, i, multiInfo);
                }

                multiInfo.tv_publishtime.setText(DateUtil.getRegionTime(contentItem.getPublishTime()));
            }
//			else if (contentType.equalsIgnoreCase("3"))
//			{ //音频
//
//			}
//			else if (contentType.equalsIgnoreCase("4"))
//			{ //视频
//
//			}
            else if (contentType.equalsIgnoreCase("5")) { //图集
                view = LayoutInflater.from(mContext).inflate(R.layout.region_imageset_item, null);
                imagesetViewHolder imageset = new imagesetViewHolder();
                imageset.tv_imageset_title = (TextView) view.findViewById(R.id.tv_imageset_title);
                imageset.tv_imageset_introduce = (TextView) view.findViewById(R.id.tv_imageset_introduce);

                imageset.im_imageset_image3 = (ImageView) view.findViewById(R.id.im_imageset_image3);
                imageset.im_imageset_image2 = (ImageView) view.findViewById(R.id.im_imageset_image2);
                imageset.im_imageset_image1 = (ImageView) view.findViewById(R.id.im_imageset_image1);

                imageset.tv_publishtime = (TextView) view.findViewById(R.id.tv_publishtime);
                imageset.tv_comments_count = (TextView) view.findViewById(R.id.tv_comments_count);
                imageset.im_comments = (ImageView) view.findViewById(R.id.im_comments);

                imageset.fl_imageset = (FrameLayout) view.findViewById(R.id.fl_imageset);
                imageset.fl_imageset.setTag(position);
                imageset.fl_imageset.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Object objUrl = v.getTag();
                        if (objUrl == null) return;
                        int pos = (Integer) objUrl;
                        //todo 直接跳转到查看图片集
                        gotoImageViewerActivity(pos/*,2*/);
                    }
                });

                //填充数据
                ImageCollection imageSet = contentItem.getImageSet();
                imageset.tv_imageset_title.setText(imageSet.getTitle());
                imageset.tv_imageset_introduce.setText(imageSet.getShortDesc());
//				imageset.im_imageset_image1.setImageUrl(imageSet.getCoverImageUrl(), R.drawable.bg_big_image);
                PicassoUtil.load(mContext, imageSet.getCoverImageUrl(), R.drawable.bg_big_image, imageset.im_imageset_image1);

                imageset.tv_publishtime.setText(DateUtil.getRegionTime(contentItem.getPublishTime()));
                imageset.tv_comments_count.setText(imageSet.getCommentNum() + "");
                imageset.im_comments.setTag("4" + REGION_SPLITOR + imageSet.getImageCollectionId());//图集
                imageset.im_comments.setOnClickListener(commentsOnclickListener);
            } else if (contentType.equalsIgnoreCase("6")) { //单本书籍
                view = LayoutInflater.from(mContext).inflate(R.layout.region_singlebook_item, null);
                SingleBookViewHolder singlebook = new SingleBookViewHolder();
                singlebook.tv_book_title = (TextView) view.findViewById(R.id.tv_book_title);
                singlebook.tv_book_name = (TextView) view.findViewById(R.id.tv_book_name);
                singlebook.tv_book_author = (TextView) view.findViewById(R.id.tv_book_author);
                singlebook.tv_book_lookedcount = (TextView) view.findViewById(R.id.tv_book_lookedcount);
                singlebook.tv_book_introduce = (TextView) view.findViewById(R.id.tv_book_introduce);
                singlebook.im_book_cover = (BookCoverView) view.findViewById(R.id.im_book_cover);
//				singlebook.im_book_cover = (SmartImageView)view.findViewById(R.id.im_book_cover);

                singlebook.tv_publishtime = (TextView) view.findViewById(R.id.tv_publishtime);
                singlebook.tv_comments_count = (TextView) view.findViewById(R.id.tv_comments_count);
                singlebook.im_comments = (ImageView) view.findViewById(R.id.im_comments);
                // 填充数据
                SingleBook singleBook = contentItem.getSingleBook();
                singlebook.tv_book_title.setText(singleBook.getTitle());
                BookInfo bookInfo = singleBook.getBookInfo();
                if (bookInfo != null) {
                    singlebook.tv_book_name.setText(bookInfo.getName());
                    singlebook.tv_book_author.setText("作者: " + bookInfo.getAuthor());
                    String introduce = singleBook.getShortDesc();
                    if (Util.isEmpty(introduce)) {
                        introduce = bookInfo.getEditorRecommend();
                        if (Util.isEmpty(introduce)) {
                            introduce = bookInfo.getShortIntro();
                        }
                    }
                    singlebook.tv_book_introduce.setText(introduce);
                    singlebook.im_book_cover.setImageUrl(bookInfo.getLogoUrl(), bookInfo.getCoverTagPicUrl());
//					singlebook.im_book_cover.setImageUrl(bookInfo.getLogoUrl());

                    singlebook.tv_publishtime.setText(DateUtil.getRegionTime(contentItem.getPublishTime()));
                    singlebook.tv_comments_count.setText(singleBook.getCommentNum() + "");
                    singlebook.im_comments.setTag("1" + REGION_SPLITOR + bookInfo.getBookId());//书籍
                    singlebook.im_comments.setOnClickListener(commentsOnclickListener);
                }
            }
            views.put(position, view);
            //TODO
            return view;
        }
    }

    private void setMultiNewsContent(int position1, int position2, MultiinfoViewHolder multiInfo) {
        RegionContentItemBean contentItem = mContentItemList.get(position1);
        MultiNews multiNews = contentItem.getMutilNews();
        TextView tv_title = null, tv_splitor = null;
        ImageView im_image = null;
        View frame = null;

        if (position2 == 0) {
            frame = multiInfo.fl_biginfo;
            tv_title = multiInfo.tv_biginfo_title;
            im_image = multiInfo.im_bigimage;
        }

        if (position2 == 1) {
            tv_splitor = multiInfo.tv_splitor1;
            frame = multiInfo.rl_smallinfo1;
            tv_title = multiInfo.tv_smallinfo1;
            im_image = multiInfo.im_smallimage1;
        }
        if (position2 == 2) {
            tv_splitor = multiInfo.tv_splitor2;
            frame = multiInfo.rl_smallinfo2;
            tv_title = multiInfo.tv_smallinfo2;
            im_image = multiInfo.im_smallimage2;
        }
        if (position2 == 3) {
            tv_splitor = multiInfo.tv_splitor3;
            frame = multiInfo.rl_smallinfo3;
            tv_title = multiInfo.tv_smallinfo3;
            im_image = multiInfo.im_smallimage3;
        }

        int defaultImgRes;
        if (position2 != 0) {
            tv_splitor.setVisibility(View.VISIBLE);
            defaultImgRes = R.drawable.bg_small_image;

        } else {
            defaultImgRes = R.drawable.bg_big_image;
        }

        frame.setVisibility(View.VISIBLE);
        frame.setOnClickListener(multiIfoOnclickListener);
        String tagSring = "" + position1 + REGION_SPLITOR + position2;
        frame.setTag(tagSring);
        //根据不同的类型，可能填充不同的内容
        String DesStr = "";
        String contentType = multiNews.getNewsType(position2);
        if (contentType.equalsIgnoreCase("1")) { //单条资讯
            SingleNews singleNews = (SingleNews) multiNews.getNewsObject(position2);
            DesStr = singleNews.getTitle();
            tv_title.setText(DesStr);
//			im_image.setImageUrl(singleNews.getCoverImageUrl(), defaultImgRes);
            PicassoUtil.load(mContext, singleNews.getCoverImageUrl(), defaultImgRes, im_image);
        } else if (contentType.equalsIgnoreCase("3")) {//音频
            AudioAndVideo audioNews = (AudioAndVideo) multiNews.getNewsObject(position2);
            DesStr = audioNews.getTitle();
            tv_title.setText(DesStr);
//			im_image.setImageUrl(audioNews.getCoverImageUrl(), defaultImgRes);
            PicassoUtil.load(mContext, audioNews.getCoverImageUrl(), defaultImgRes, im_image);
        } else if (contentType.equalsIgnoreCase("4")) {//视频
            AudioAndVideo videoNews = (AudioAndVideo) multiNews.getNewsObject(position2);
            DesStr = videoNews.getTitle();
            tv_title.setText(DesStr);
//			im_image.setImageUrl(videoNews.getCoverImageUrl(), defaultImgRes);
            PicassoUtil.load(mContext, videoNews.getCoverImageUrl(), defaultImgRes, im_image);
        } else if (contentType.equalsIgnoreCase("5")) { //图集
            ImageCollection imgsSet = (ImageCollection) multiNews.getNewsObject(position2);
            DesStr = imgsSet.getTitle();
            tv_title.setText(DesStr);
//			im_image.setImageUrl(imgsSet.getCoverImageUrl(), defaultImgRes);
            PicassoUtil.load(mContext, imgsSet.getCoverImageUrl(), defaultImgRes, im_image);
        } else if (contentType.equalsIgnoreCase("6")) { //单本书籍
            SingleBook singleBook = (SingleBook) multiNews.getNewsObject(position2);
            DesStr = singleBook.getTitle();
            tv_title.setText(DesStr);
            BookInfo bookInfo = singleBook.getBookInfo();
            String url = "";
            if (bookInfo != null) {
                url = bookInfo.getLogoUrl();
            }
            if (Util.isEmpty(url)) {
                url = singleBook.getCoverImageUrl();
            }
//			im_image.setImageUrl(url, defaultImgRes);
            PicassoUtil.load(mContext, url, defaultImgRes, im_image);
        }
    }

    OnClickListener commentsOnclickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Object objTarget = v.getTag();
            if (objTarget == null) return;
            String strTarget = (String) objTarget;
            int splitorPos = strTarget.indexOf(REGION_SPLITOR);
            targetType = strTarget.substring(0, splitorPos);
            targetValue = strTarget.substring(splitorPos + 1);
            RelativeLayout parent = (RelativeLayout) v.getParent();
            tv_comments_count = (TextView) parent.findViewById(R.id.tv_comments_count);
            Intent intent1 = new Intent();
            intent1.setClass(mContext, CommentListActivity.class);
            intent1.putExtra(DefaultConsts.COMMENT_TARGET_TYPE, targetType);
            intent1.putExtra(DefaultConsts.COMMENT_TARGET_VALUE, targetValue);
            baseActivity.startActivityForResult(intent1, BaseBusinessActivity.COMMENTS_REQUEST_CODE);
        }
    };

    OnClickListener multiIfoOnclickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            Object objPositions = v.getTag();
            if (objPositions == null) return;
            String positions = (String) objPositions;
            int splitorPos = positions.indexOf(REGION_SPLITOR);
            int position1 = Integer.parseInt(positions.substring(0, splitorPos));
            int position2 = Integer.parseInt(positions.substring(splitorPos + 1));
            //todo 跳转到图文详情
            //gotoImageTextActivity(url, title);
            RegionContentItemBean contentItem = mContentItemList.get(position1);
            MultiNews multiNews = contentItem.getMutilNews();
            String contentType = multiNews.getNewsType(position2);
            if (contentType.equalsIgnoreCase("1")) { //单条资讯
                //todo 跳转到图文详情
                SingleNews singleNews = (SingleNews) multiNews.getNewsObject(position2);
                gotoImageTextActivity(singleNews.getHtmlUrl(), singleNews.getTitle(), singleNews.getModelContentDetailId() + "");
            } else if (contentType.equalsIgnoreCase("3")) {//音频
                // 跳转到图文详情
                AudioAndVideo audioNews = (AudioAndVideo) multiNews.getNewsObject(position2);
                gotoImageTextActivity(audioNews.getHtmlUrl(), audioNews.getTitle(), audioNews.getModelContentDetailId() + "");
            } else if (contentType.equalsIgnoreCase("4")) {//视频
                // 跳转到图文详情
                AudioAndVideo videoNews = (AudioAndVideo) multiNews.getNewsObject(position2);
                gotoImageTextActivity(videoNews.getHtmlUrl(), videoNews.getTitle(), videoNews.getModelContentDetailId() + "");
            } else if (contentType.equalsIgnoreCase("5")) { //图集
                //todo 跳转到查看图集图片
                ImageCollection imageSet = (ImageCollection) multiNews.getNewsObject(position2);
                int imgCounts = imageSet.getImageCollectionNum();
                Intent intent;
                if (imgCounts == 0) {
                    Toast.makeText(mContext, "图集已下架", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (imgCounts <= IMAGE_COUNT) {
                    //直接进入看图片
                    intent = new Intent(mContext, AtlasSeeActivity.class);
                    intent.putExtra(AtlasSeeActivity.FROM_TYPE, DefaultConsts.TAG_FROM_ENTERPRISE);
                    intent.putExtra(AtlasSeeActivity.IMAGE_COUNT, imgCounts);
                } else {//进入到瀑布流页面
                    intent = new Intent(mContext, AtlasActivity.class);
                    intent.putExtra(AtlasActivity.ATLAS_NAME, imageSet.getTitle());
                }
                //设置图集的数据
                intent.putExtra(AtlasActivity.ATLAS_ID, imageSet.getImageCollectionId());
                mContext.startActivity(intent);

            } else if (contentType.equalsIgnoreCase("6")) { //单本书籍
                //跳转到书籍详情
                SingleBook singleBook = (SingleBook) multiNews.getNewsObject(position2);
                BookInfo bookInfo = singleBook.getBookInfo();
                if (bookInfo == null) return;
                //#ifdef SHOW_OLDBOOKDETAIL
                //$ Intent intent = new Intent(mContext, BookDetailActivity.class);
                //#else
                Intent intent = new Intent(mContext, NewBookDetailActivity.class);
                //#endif
                bookInfo.setAuthor("");
                intent.putExtra("BookInfo", bookInfo);
                mContext.startActivity(intent);
            }
        }
    };

    private static class SingleinfoViewHolder {
        TextView tv_publishtime, tv_info_title, tv_info_from, tv_item_introduce;
        ImageView im_bigimage, im_leftimage, im_rightimage;
        TextView tv_comments_count;
        ImageView im_comments;
    }

    private static class MultiinfoViewHolder {
        TextView tv_publishtime, tv_biginfo_title, tv_smallinfo1, tv_smallinfo2, tv_smallinfo3;
        TextView tv_splitor1, tv_splitor2, tv_splitor3;
        ImageView im_bigimage, im_smallimage1, im_smallimage2, im_smallimage3;
        View fl_biginfo;
        View rl_smallinfo1, rl_smallinfo2, rl_smallinfo3;
    }

    private static class SingleBookViewHolder {
        TextView tv_publishtime, tv_book_title, tv_book_name, tv_book_author, tv_book_lookedcount, tv_book_introduce;
        BookCoverView im_book_cover;
        //		SmartImageView im_book_cover;
        TextView tv_comments_count;
        ImageView im_comments;
    }

    private static class imagesetViewHolder {
        TextView tv_publishtime, tv_imageset_title, tv_imageset_introduce;
        ImageView im_imageset_image3, im_imageset_image2, im_imageset_image1;
        FrameLayout fl_imageset;
        TextView tv_comments_count;
        ImageView im_comments;
    }

    /******************************
     * 一些私有的方法
     *****************************************/

    private void getContentItemDatas() {
//		RegionContentAction contentAction = new RegionContentAction(mContext, new ContentActionListener() );
//		contentAction.start();
        //加载企业动态列表
        NewActionHelp.qryModuleContentList(mContext, moduleId, currentPublishTime, PAGESIZE, new ObjectHttpResponseHandler<Map<String, List<RegionContentItemBean>>>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("111111Fail", "qryModuleContentList" + s);
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (contentViewListener != null) {
                            contentViewListener.OnLoadDataCompleted(2);//装载更多
                        }
                        updateSwitchView(-1);//加载失败
                    }
                });
            }

            @Override
            public void onSuccess(int i, Header[] headers, Map<String, List<RegionContentItemBean>> stringListMap, String s) {
                Log.e("111111OK", "qryModuleContentList" + s);
                List<RegionContentItemBean> contentItems = stringListMap.get("modelContentList");
                removeAudioAndVideo(contentItems);//临时移除音视频的数据
                if (contentItems == null || contentItems.size() == 0) {
                    //取到的内空为空
                    hasMore = false;
                    baseActivity.getUIHandler().post(new Runnable() {
                        @Override
                        public void run() {
                            if (contentViewListener != null) {
                                contentViewListener.OnLoadDataCompleted(2);//装载更多
                            }
                            if (currentPage == 1) {//只有当前是重新刷新时， 才更新ui为无内容
                                updateSwitchView(2);//内容为空
                            }
                        }
                    });
                    return;
                }
                hasMore = contentItems.size() >= PAGESIZE;
                if (currentPage == 1) {//刷新
                    mContentItemList = contentItems;
                } else {//取下一页
                    mContentItemList.addAll(contentItems);
                }
                RegionContentItemBean lastItem = mContentItemList.get(mContentItemList.size() - 1);
                currentPublishTime = lastItem.getPublishTime();
                //刷新UI
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        refreshUIData();
                    }
                });
            }

            @Override
            public Type getType() {
                return new TypeToken<Map<String, List<RegionContentItemBean>>>() {
                }.getType();
            }
        });
    }

    private void getFakeContentItemDatas() {
        for (int i = 0; i < 10; i++) {
            mContentItemList.add(RegionContentItemBean.generateContentItem());
        }
    }

    /**
     * 栏目切换加载动画
     *
     * @param flag 0:加载中，1：加载完成，2: 内容为空  -1：加载失败
     */
    private void updateSwitchView(int flag) {
        switch (flag) {
            case -1:
                switchView.setVisibility(View.VISIBLE);
                rl_blank_content.setVisibility(View.GONE);
                mContentListView.setVisibility(View.GONE);
                if (switchDrawable != null && switchDrawable.isRunning()) {
                    switchDrawable.stop();
                }
                //TODO
                switchImg.setBackgroundResource(R.drawable.home_loading_fail);
                break;
            case 0:
                switchView.setVisibility(View.VISIBLE);
                mContentListView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.GONE);
                switchImg.setBackgroundResource(R.drawable.home_progress);
//				switchImg.setBackgroundResource(R.anim.column_switch_anim);
                switchDrawable = (AnimationDrawable) switchImg.getBackground();
                switchDrawable.start();
                break;
            case 1:
                switchView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.GONE);
                mContentListView.setVisibility(View.VISIBLE);
                break;
            case 2:
                switchView.setVisibility(View.GONE);
                rl_blank_content.setVisibility(View.VISIBLE);
                mContentListView.setVisibility(View.GONE);
                break;
        }
    }

    private void removeAudioAndVideo(List<RegionContentItemBean> contentItems) {
        if (contentItems == null || contentItems.size() == 0) return;
        for (int i = 0; i < contentItems.size(); i++) {
            RegionContentItemBean contentItem = contentItems.get(i);
            String type = contentItem.getType();
            if (type.equalsIgnoreCase("3") || type.equalsIgnoreCase("4")) {
                contentItems.remove(contentItem);
                i--;
            }
        }
    }

    /**
     * 获取专区内容的action 类
     */
    private class RegionContentAction extends AbstractHttpPostDracom {
        public RegionContentAction(Context context, ActionListener actionListener) {
            super(context, "qryModuleContentList.do", actionListener);
        }

        @Override
        public void getParameter(HashMap<String, String> parameter_map) {
            parameter_map.put("account", Const.phone_number);
            parameter_map.put("enterpriseId", AppConfig.getEnterpriseId());

            parameter_map.put("moduleId", moduleId + "");
            parameter_map.put("currentPublishTime", currentPublishTime + "");
            parameter_map.put("length", PAGESIZE + "");

            parameter_map.put("timeStamp", String.valueOf(timeStamp));
            parameter_map.put("cid", cid(Const.phone_number + Const.ACCOUNTTYPE + Const.CLIENTTYPE + timeStamp + AppConfig.getEnterpriseId() + moduleId + currentPublishTime + PAGESIZE));
        }

        @Override
        public void doResponseXml(String xml) {
            println(xml);
            int result = -1;
            try {
                JSONObject jsonObject = new JSONObject(xml);
                result = jsonObject.getInt("resultCode");
                if (result == 1000) {
                    List<RegionContentItemBean> contentItems;
                    JSONObject contentJsonObject = new JSONObject(jsonObject.getString("returnObject"));
                    Gson gson = new Gson();
                    String contentStr = contentJsonObject.getString("modelContentList");
                    contentItems = gson.fromJson(contentStr, new TypeToken<List<RegionContentItemBean>>() {
                    }.getType());
                    listener.OK(contentItems);
                } else {
                    listener.ERROR(result, ResultCode.getResultText(result));
                }
            } catch (Exception e) {
                e.printStackTrace();
                listener.ERROR(-1, "系统错误");
            }
        }

        @Override
        protected void doRequestHeader(HashMap<String, String> header_map) {

        }

        @Override
        public void dispose() {

        }
    }

    /**
     * 获取企业专区的数据 action listener
     */
    private class ContentActionListener
            extends
            BaseAction {
        @SuppressWarnings("unchecked")
        @Override
        public void OK(Object obj) {
            List<RegionContentItemBean> contentItems = (List<RegionContentItemBean>) obj;
            removeAudioAndVideo(contentItems);//临时移除音视频的数据
            if (contentItems == null || contentItems.size() == 0) {
                //取到的内空为空
                hasMore = false;
                baseActivity.getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        if (contentViewListener != null) {
                            contentViewListener.OnLoadDataCompleted(2);//装载更多
                        }
                        if (currentPage == 1) {//只有当前是重新刷新时， 才更新ui为无内容
                            updateSwitchView(2);//内容为空
                        }
                    }
                });
                return;
            }
            hasMore = contentItems.size() >= PAGESIZE;
            if (currentPage == 1) {//刷新
                mContentItemList = contentItems;
            } else {//取下一页
                mContentItemList.addAll(contentItems);
            }
            RegionContentItemBean lastItem = mContentItemList.get(mContentItemList.size() - 1);
            currentPublishTime = lastItem.getPublishTime();
            //刷新UI
            baseActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    refreshUIData();
                }
            });
        }

        @Override
        public void onError() {
            super.onError();
            //通知 外部的调用者， 出错了。
            baseActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    if (contentViewListener != null) {
                        contentViewListener.OnLoadDataCompleted(2);//装载更多
                    }
                    updateSwitchView(-1);//加载失败
                }
            });
        }
    }

    /**
     * 获取内容项评论数的 action listener
     */
    private class BookCommentsNumberActionListener
            extends
            BaseAction {
        @SuppressWarnings("unchecked")
        @Override
        public void OK(Object obj) {
            NumberInfo numbers = (NumberInfo) obj;
            final int commentsCount = numbers.commentNum;
            //更新UI上的评论数
            baseActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    //更新UI
                    tv_comments_count.setText(commentsCount + "");
                }
            });
        }

        @Override
        public void onError() {
            super.onError();
            //通知 外部的调用者， 出错了。
            baseActivity.getUIHandler().post(new Runnable() {
                @Override
                public void run() {
                    //todo 处理UI的不同显示
                    Util.showToast(mContext, "获取评论数失败");
                }
            });
        }
    }

    public static interface RegionContentViewListener {
        /**
         * @param flag 1为首次装载， 2 为装载更多
         */
        public void OnLoadDataCompleted(int flag);
    }


    public int getDataSize() {
        return (mContentItemList == null || mContentItemList.isEmpty()) ? 0 : mContentItemList.size();
    }
}
